import logging
from django.utils.timezone import localtime

# 获取logger
logger = logging.getLogger('mylogger')


class RequestLoggingMiddleware:
    """
    中间件：记录所有传入请求的日志
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 记录请求的日志
        logger.info(f"Request: {request.method} {request.path} at {localtime()}")

        # 处理请求
        response = self.get_response(request)

        response_code = response.data.get('code', None) if hasattr(response, 'data') else None

        if response_code is not None:
            logger.info(f"Response: {response_code} for {request.method} {request.path}")
        else:
            logger.info(f"Response: {response.status_code} for {request.method} {request.path}")

        return response
